
module spi_clk (
    input                           clk_i,
    input                           rstn_i,

    input                           csn_i,
    input   [31:0]                  cnt_i,
    input                           spi_clk_mode_i,
    
    output reg                      spi_CLK_o,
    output                          spi_CLK_pos_r_o,
    output reg                      spi_CLK_pos_e_o,
    output                          spi_CLK_neg_r_o        
);

reg [31:0]                          cnt;
wire                                cnt_flag;
reg                                 spi_CLK_o_d1;

assign cnt_flag = (cnt == cnt_i-1) ? 1'b1 : 1'b0;
always@(posedge clk_i or negedge rstn_i)begin
    if(!rstn_i)begin
        cnt <= 'd0;
    end
    else if(csn_i) begin
        cnt <= 'd0;
    end
    else if(cnt_flag)begin
        cnt <= 'd0;
    end
    else begin
        cnt <= cnt + 1'b1;
    end
end 

always@(posedge clk_i or negedge rstn_i)begin
    if(!rstn_i)begin
        spi_CLK_o <= spi_clk_mode_i ? 1'b1 : 1'b0;
    end
    else begin
        if(!csn_i) begin
            spi_CLK_o <= cnt_flag ? ~spi_CLK_o : spi_CLK_o;
        end
        else begin
            spi_CLK_o <= spi_clk_mode_i ? 1'b1 : 1'b0;
        end
    end
end

always@(posedge clk_i or negedge rstn_i)begin
    if(!rstn_i)begin
        spi_CLK_pos_e_o <= 'd0;
    end
    else if ((cnt == (cnt_i>>1)-1) && !spi_CLK_o) begin
        spi_CLK_pos_e_o <= 'b1;
    end
    else begin
       spi_CLK_pos_e_o <= 'd0;
    end
end

always@(posedge clk_i or negedge rstn_i)begin
    if(!rstn_i)begin
        spi_CLK_o_d1 <= 1'b0;
    end
    else begin
        spi_CLK_o_d1 <= spi_CLK_o;
    end
end

assign spi_CLK_neg_r_o = ~spi_CLK_o     & spi_CLK_o_d1  ;
assign spi_CLK_pos_r_o = ~spi_CLK_o_d1  & spi_CLK_o     ;

endmodule